<template>
  <div class="relative leading-[0]">
    <!-- 单行 -->
    <input
      v-if="type === TYPE_TEXT"
      class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border outline-0 py-0.5 px-1 text-sm rounded-sm focus:border-blue-400 w-full"
      type="text"
      :value="modelValue"
      :maxlength="max"
      @input="$emit('update:modelValue', $event.target.value)"
    />
    <!-- 多行 -->
    <textarea
      v-if="type === TYPE_TEXTAREA"
      class="border-gray-200 dark:border-zinc-600 dark:bg-zinc-800 duration-100 dark:text-zinc-400 border outline-0 py-0.5 px-1 text-sm rounded-sm focus:border-blue-400 w-full"
      type="text"
      :value="modelValue"
      rows="5"
      :maxlength="max"
      @input="$emit('update:modelValue', $event.target.value)"
    ></textarea>
    <!-- 长度 -->
    <span
      v-if="max"
      class="absolute right-1 bottom-0.5 text-xs"
      :class="{
        'text-red-500': currentNumber === Number(max)
      }"
      >{{ currentNumber }}/{{ max }}</span
    >
  </div>
</template>

<script setup>
import { TYPE_TEXT, TYPE_TEXTAREA } from '@/constants/input'
import { computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    required: true
  },
  //type
  type: {
    type: String,
    default: TYPE_TEXT,
    validator: (value) => {
      const result = [TYPE_TEXT, TYPE_TEXTAREA].includes(value)
      if (!result) {
        throw new Error('type 类型错误')
      }
      return result
    }
  },
  // max
  max: {
    type: [Number, String]
  }
})

defineEmits(['update:modelValue'])

// 计算属性，当前输入的字数
const currentNumber = computed(() => {
  return props.modelValue.length
})
</script>

<style lang="scss" scoped></style>
